﻿using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace furion.blog.Utils.Extensions
{
    public static class HttpRequestExtension
    {
		/// <summary>
		/// 获得body请求
		/// </summary>
		/// <param name="request"></param>
		/// <returns></returns>
		public static string GetBodyData(this HttpRequest request)
		{
			request.EnableBuffering();
			// 改方法 StreamReader释放的时候，也会把request.Body对象释放掉，然后以后的请求就不能再次读取request.Body了
			/*
			request.Body.Seek(0, SeekOrigin.Begin);
			using (var reader = new StreamReader(request.Body, Encoding.UTF8))
			{
				var param = reader.ReadToEnd();
				return param;
			}
			*/

			// 这里由于没有释放StreamReader 担心内存问题
			/*
			string body = "";
			// 获取请求参数
			long? length = request.HttpContext.Request.ContentLength;
			//request.HttpContext.Request.Body.Position = 0;
			request.Body.Seek(0, SeekOrigin.Begin);
			if (length != null && length > 0)
			{
				// 使用这个方式读取，并且使用异步
				StreamReader streamReader = new StreamReader(request.HttpContext.Request.Body, Encoding.UTF8);
				body = streamReader.ReadToEndAsync().Result;
			}
			return body;
			*/

			string body = "";
			var buffer = new MemoryStream();
			request.Body.Seek(0, SeekOrigin.Begin);
			request.Body.CopyTo(buffer);
			buffer.Position = 0;
			try
			{
				using (StreamReader streamReader = new StreamReader(buffer, Encoding.UTF8))
				{
					body = streamReader.ReadToEndAsync().Result;
				}
			}
			finally
			{
				if (buffer != null)
					buffer.Dispose();
			}
			return body;
		}
	}
}
